package com.gz.utils;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.gz.bean.AnnotationBean;
import com.gz.myAnnotation.Controller;
import com.gz.myAnnotation.RequestMapping;
import com.gz.myAnnotation.Result;

public class AnnotationUtils {

	
	public static Map<String, AnnotationBean> processAnnotation(String myActionPackage) throws Exception {
		Map<String, AnnotationBean> annotationMap = new HashMap();
		String classPath = "E:\\workspace\\AnnotationMVCProject\\build\\classes";
		String packPackage = myActionPackage.replaceAll(".", "\\");
		File dir = new File(classPath + packPackage);
		File[] files = dir.listFiles();
		Class<?> clazz = null;
		List<Class<?>> clazzList = new ArrayList<Class<?>>();

		for (File f : files) {
			clazz = Class.forName(myActionPackage + "." + f.getName().split("\\.")[0]);
			clazzList.add(clazz);
		}

		for (Class<?> c : clazzList) {
			String controllerName = "";
			if (c.isAnnotationPresent(Controller.class)) {
				Controller controller = c.getAnnotation(Controller.class);
				controllerName = controller.name();
			}
			Method[] methods = c.getMethods();
			for (int i = 0; i < methods.length; i++) {
				AnnotationBean annotationBean=new AnnotationBean();
				annotationBean.setActionPath(controllerName);
				String temp=controllerName.replace("/", "");
				temp=temp.substring(0, 1).toUpperCase()+temp.substring(1,temp.length()-1);
				annotationBean.setBeanName(temp);
				annotationBean.setBeanClass(myActionPackage.replace("action.impl", "pojo")+temp);
				annotationBean.setActionName(temp);
				annotationBean.setActionClass(myActionPackage+"."+temp+"Action");
				if (methods[i].isAnnotationPresent(RequestMapping.class)) {
					RequestMapping requestMapping = methods[i].getAnnotation(RequestMapping.class);
					Map<String,String> actionForward=new HashMap<String,String>();
					Result[] rs = requestMapping.results();
					for (Result r : rs) {
						actionForward.put(r.name(), r.value());
					}
					annotationBean.setActionForward(actionForward);
				}
				annotationMap.put(controllerName, annotationBean);
			}

		}

		return annotationMap;
	}
}
